package com.jingbian.cppccbackend.controller.admin;

import com.jingbian.cppccbackend.entity.Meetings;
import com.jingbian.cppccbackend.entity.Result;
import com.jingbian.cppccbackend.entity.Users;
import com.jingbian.cppccbackend.entity.dto.AddMeetingDTO;
import com.jingbian.cppccbackend.entity.dto.UpdateMeetingDTO;
import com.jingbian.cppccbackend.service.admin.MeetingsService;
import com.jingbian.cppccbackend.utils.ResultUtil;
import com.jingbian.cppccbackend.entity.vo.MeetingDetailVO;
import com.jingbian.cppccbackend.entity.vo.PageVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * <p>
 * 普通签到发起 前端控制器
 * </p>
 *
 * @author yezi
 * @since 2025-02-26
 */
@Slf4j
@RestController
@RequestMapping("/admins/signs")
public class adminSignsController {
    @Autowired
    private MeetingsService meetingsService;

    //获取签到数据（没有结束的签到）
    @GetMapping("/getSigns")
    public Result<PageVO<Meetings>> getSigns(
            Integer pageNum,
            Integer pageSize,
            @RequestParam(required = false,defaultValue = "asc") String sortType,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(required = false) String searchText,
            @RequestParam(required = false) String status
    ) {
        PageVO<Meetings> signs = meetingsService.getMeetings(
                pageNum, pageSize, sortType, startDate, endDate, searchText, status, false);
        return ResultUtil.success(signs);
    }

    //获取已结束的签到数据
    @GetMapping("/getEndedSigns")
    public Result<PageVO<Meetings>> getEndedSigns(
            Integer pageNum,
            Integer pageSize,
            @RequestParam(required = false,defaultValue = "desc") String sortType,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(required = false) String searchText,
            @RequestParam(required = false) String status
    ) {
        PageVO<Meetings> signs = meetingsService.getEndedMeetings(
                pageNum, pageSize, sortType, startDate, endDate, searchText, status, false);
        return ResultUtil.success(signs);
    }

    //导出签到数据
    @GetMapping("/exportEndedSigns")
    public ResponseEntity<byte[]> exportSigns(
            @RequestParam(required = false,defaultValue = "asc") String sortType,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(required = false) String searchText,
            @RequestParam(required = false) String status) throws IOException {
        log.info("开始导出签到列表Excel，参数：sortType={}, startDate={}, endDate={}, searchText={},status={} ",
                sortType, startDate, endDate, status, searchText);

        try {
            // 获取签到列表数据
            List<Meetings> signsList = meetingsService.getMeetingsList(sortType, startDate, endDate, searchText, status, false);
            log.info("获取到 {} 条数据", signsList.size());

            // 创建工作簿
            try (XSSFWorkbook workbook = new XSSFWorkbook()) {
                Sheet sheet = workbook.createSheet("签到列表");

                // 设置表头样式
                CellStyle headerStyle = workbook.createCellStyle();
                headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
                headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
                Font headerFont = workbook.createFont();
                headerFont.setBold(true);
                headerStyle.setFont(headerFont);

                // 创建表头
                Row headerRow = sheet.createRow(0);
                String[] header = {"签到标题", "签到说明", "组织者", "签到开始时间", "签到截止时间", "签到地点", "具体地点", "发起时间"};

                for (int i = 0; i < header.length; i++) {
                    Cell cell = headerRow.createCell(i);
                    cell.setCellValue(header[i]);
                    cell.setCellStyle(headerStyle);
                    sheet.autoSizeColumn(i);
                }

                // 填充数据
                int rowNum = 1;
                for (Meetings sign : signsList) {
                    Row row = sheet.createRow(rowNum++);
                    row.createCell(0).setCellValue(sign.getTitle());
                    row.createCell(1).setCellValue(sign.getIntroduction());
                    row.createCell(2).setCellValue(sign.getOrganizer());

                    // 设置签到开始时间
                    Cell startTimeCell = row.createCell(3);
                    startTimeCell.setCellValue(sign.getStartTime());
                    CellStyle dateStyle = workbook.createCellStyle();
                    dateStyle.setDataFormat(workbook.createDataFormat().getFormat("yyyy-mm-dd hh:mm"));
                    startTimeCell.setCellStyle(dateStyle);

                    // 设置结束时间
                    Cell endTimeCell = row.createCell(4);
                    endTimeCell.setCellValue(sign.getEndTime());
                    endTimeCell.setCellStyle(dateStyle);

                    row.createCell(5).setCellValue(sign.getLocation1());
                    row.createCell(6).setCellValue(sign.getLocation2());

                    // 设置发起时间
                    Cell submissionTimeCell = row.createCell(7);
                    submissionTimeCell.setCellValue(sign.getCreatedAt());
                    submissionTimeCell.setCellStyle(dateStyle);
                }

                // 写入字节数组
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                workbook.write(outputStream);
                byte[] content = outputStream.toByteArray();

                // 设置响应头
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
                String filename = URLEncoder.encode("签到列表.xlsx", StandardCharsets.UTF_8).replaceAll("\\+", "%20");
                headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename*=UTF-8''" + filename);

                log.info("Excel文件生成成功，大小: {} bytes", content.length);
                return new ResponseEntity<>(content, headers, HttpStatus.OK);
            }
        } catch (Exception e) {
            log.error("导出Excel失败", e);
            throw new RuntimeException("导出Excel失败: " + e.getMessage());
        }
    }

    //获取签到详情及签到情况
    @GetMapping("/getSignDetail/{mid}")
    public Result<MeetingDetailVO> getSignDetail(@PathVariable Integer mid) {
        MeetingDetailVO signDetail = meetingsService.getMeetingDetail(mid);
        if (signDetail == null) {
            return ResultUtil.fail("未找到该签到信息");
        }

        return ResultUtil.success(signDetail);
    }

    //获取用户数据（用来选择签到人员）
    @GetMapping("/getParticipants")
    public Result<List<Users>> getParticipants(
            @RequestParam(required = false) String identity,
            @RequestParam(required = false) String region,
            @RequestParam(required = false) String affiliation,
            @RequestParam(required = false) String searchText
    ) {
        List<Users> users = meetingsService.getParticipants(identity, region, affiliation, searchText);
        return ResultUtil.success(users);
    }

    @PostMapping("/addSign")
    public Result<?> addSign(@RequestBody AddMeetingDTO signDTO) {
        try {
            // 设置为签到数据
            signDTO.setIsMeeting(false);
            boolean success = meetingsService.addMeeting(signDTO);
            if (success) {
                return ResultUtil.success("签到发起成功");
            } else {
                return ResultUtil.fail("签到发起失败");
            }
        } catch (Exception e) {
            log.error("签到发起失败", e);
            return ResultUtil.fail("签到发起失败：" + e.getMessage());
        }
    }

    @PutMapping("/updateSign")
    public Result<?> updateSign(@RequestBody UpdateMeetingDTO updateSignDTO) {
        try {
            // 验证是否为签到数据
            MeetingDetailVO detail = meetingsService.getMeetingDetail(updateSignDTO.getMid());
            if (detail == null) {
                return ResultUtil.fail("未找到该签到信息");
            }

            // 设置为签到数据
            updateSignDTO.setIsMeeting(false);
            boolean success = meetingsService.updateMeeting(updateSignDTO);
            if (success) {
                return ResultUtil.success("签到修改成功");
            } else {
                return ResultUtil.fail("签到修改失败");
            }
        } catch (Exception e) {
            log.error("修改签到失败", e);
            return ResultUtil.fail("修改签到失败: " + e.getMessage());
        }
    }

    @DeleteMapping("/deleteSign/{mid}")
    public Result<?> deleteSign(@PathVariable Integer mid) {
        try {
            // 验证是否为签到数据
            MeetingDetailVO detail = meetingsService.getMeetingDetail(mid);
            if (detail == null) {
                return ResultUtil.fail("未找到该签到信息");
            }


            boolean success = meetingsService.removeById(mid);
            if (success) {
                return ResultUtil.success("签到删除成功");
            } else {
                return ResultUtil.fail("签到删除失败");
            }
        } catch (Exception e) {
            log.error("删除签到失败", e);
            return ResultUtil.fail("删除签到失败: " + e.getMessage());
        }
    }
}
